<template>
  <el-form label-width="80px" ref="loginFormRef" :model="loginForm" :rules="loginRules" size="large">
    <el-form-item label="用户名" prop="username">
      <el-input style="height: 35px; width: 120px" v-model="loginForm.username">
        <!--        <template #prefix>-->
        <!--          <el-icon class="el-input__icon">-->
        <!--            <user />-->
        <!--          </el-icon>-->
        <!--        </template>-->
      </el-input>
    </el-form-item>
    <el-form-item label="密码" prop="password">
      <el-input style="height: 35px" v-model="loginForm.password" type="password" show-password autocomplete="new-password">
        <!--        <template #prefix>-->
        <!--          <el-icon class="el-input__icon">-->
        <!--            <lock />-->
        <!--          </el-icon>-->
        <!--        </template>-->
      </el-input>
    </el-form-item>
    <el-form-item label="验证码" prop="verifcode">
      <el-input style="height: 35px" v-model="loginForm.verifcode" type="text">
        <!--        <template #prefix>-->
        <!--          <el-icon>-->
        <!--            <Iphone />-->
        <!--          </el-icon>-->
        <!--        </template>-->
        <template #suffix>
          <img @click="toGetLoginImage" style="cursor: pointer; filter: grayscale(1)" :src="codeUrl" alt="" />
        </template>
      </el-input>
    </el-form-item>
  </el-form>
  <div class="h-box" style="margin-left: 80px">
    <el-button size="default" :loading="loading" @click="login(loginFormRef)" style="width: 70px" type="primary">登录</el-button>
    <el-button style="width: 70px" @click="resetForm(loginFormRef)" type="default">重置</el-button>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import { HOME_URL } from "@/config";
// import { getTimeState } from "@/utils";
import { Login } from "@/api/interface";
import { ElNotification } from "element-plus";
import { loginApi, getLoginImage } from "@/api/modules/login";
import { useUserStore } from "@/stores/modules/user";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";
import { initDynamicRouter } from "@/routers/modules/dynamicRouter";
import { CircleClose, UserFilled } from "@element-plus/icons-vue";
import type { ElForm } from "element-plus";
import md5 from "md5";
import { cfg_softcheck, licenseList } from "@/api/modules/system/params";
import { cfgAppstate } from "@/api/modules/home";

const router = useRouter();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();
const loginRules = reactive({
  username: [{ required: true, message: "请输入用户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  verifcode: [{ required: true, message: "请输入验证码", trigger: "blur" }]
});

const loading = ref(false);
const loginForm = reactive<Login.ReqLoginForm>({
  username: "",
  password: "",
  verifcode: ""
});

async function getCfg() {
  if (!useUserStore().userInfo.name) return;
  const res1 = await licenseList();
  const res2 = await cfgAppstate();
  const res3 = await cfg_softcheck();
  console.log(res2);
  // useUserStore.setLicenseInfo({
  //   isLicence: res1.result.data && res1.result.data.length,
  //   license: res1.result.data[0][1] == 1 ? "测试版" : "正式版"
  // });
  localStorage.setItem(
    "LicenseInfo",
    JSON.stringify({
      isLicence: Boolean(res1.result.data && res1.result.data.length),
      license: res1.result.data[0][1],
      version: res3.version,
      licenseTime: res1.result.data[0][6],
      day: res1.result.data[0][4],
      running: res2.code > 0
    })
  );
  // if (res1.result.data && res1.result.data.length) {
  //   updateFormData.license = res1.result.data[0][1];
  //   updateFormData.request = res1.result.data[0][6];
  //   updateFormData.day = res1.result.data[0][4];
  //   updateFormData.isLicence = true;
  // } else {
  //   updateFormData.isLicence = false;
  // }
}

// login
const login = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(async valid => {
    if (!valid) return;
    loading.value = true;
    try {
      // 1.执行登录接口
      const sendData = {
        username: loginForm.username,
        userpwd: md5(loginForm.password),
        verifcode: loginForm.verifcode
      };
      const loginApiRes = await loginApi(sendData);
      console.log(`loginApiRes:`, loginApiRes);
      localStorage.setItem("role", loginApiRes?.role);
      userStore.setToken("123456");
      userStore.setUserInfo({
        name: loginForm.username
      });
      // 2.添加动态路由
      await initDynamicRouter();

      // 3.清空 tabs、keepAlive 数据
      tabsStore.setTabs([]);
      keepAliveStore.setKeepAliveName([]);

      // 4.跳转到首页

      // ElNotification({
      //   title: getTimeState(),
      //   message: "欢迎登录 Geeker-Admin",
      //   type: "success",
      //   duration: 3000
      // });
      // ElNotification({
      //   title: "提示",
      //   dangerouslyUseHTMLString: true,
      //   message: "登陆成功",
      //   type: "success",
      //   duration: 8000
      // });

      // window.location.reload();
      router.push("/home/index");
      sessionStorage.setItem("isLogin", "1");
      setTimeout(async () => {
        await getCfg();
      }, 1500);
    } catch (e) {
      toGetLoginImage();
    } finally {
      loading.value = false;
    }
  });
};

// resetForm
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

onMounted(async () => {
  await useUserStore().setAppTitle();
  toGetLoginImage();
  // 监听 enter 事件（调用登录）
  document.onkeydown = (e: KeyboardEvent) => {
    if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
      if (loading.value) return;
      login(loginFormRef.value);
    }
  };
});

onBeforeUnmount(() => {
  document.onkeydown = null;
});
const codeUrl = ref("");

async function toGetLoginImage() {
  try {
    const res = await getLoginImage();
    const url = URL.createObjectURL(res);
    console.log("getLoginImageRes:", url);
    codeUrl.value = url;
  } catch (error) {
    alert(JSON.stringify(error));
  }
}
</script>

<style scoped lang="scss">
@import "../index.scss";
</style>
